package top.lixunda.common.validate.core;

import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author Xumda
 * @version time:2019/11/19 16:02
 */
@SuppressWarnings({"WeakerAccess", "UnusedReturnValue", "unused"})
public class ValidateResult {

    private List<ValidateError> errorList;

    public ValidateResult() {
        this.errorList = new ArrayList<>(4);
    }

    public List<ValidateError> getErrorList() {
        return errorList;
    }

    public ValidateResult setErrorList(List<ValidateError> errorList) {
        this.errorList = errorList;
        return this;
    }

    public ValidateResult addErrors(ValidateError... errors) {
        if (errors == null || errors.length <= 0) {
            return this;
        }
        Collection<ValidateError> filterErrors = Arrays.stream(errors).filter(Objects::nonNull).collect(Collectors.toList());
        this.errorList.addAll(filterErrors);
        return this;
    }

    public ValidateResult addErrors(Collection<ValidateError> errors) {
        if (errors == null || errors.size() <= 0) {
            return this;
        }
        for (ValidateError error : errors) {
            if (error == null) {
                return this;
            }
        }
        Collection<ValidateError> filterErrors = errors.stream().filter(Objects::nonNull).collect(Collectors.toList());
        this.errorList.addAll(filterErrors);
        return this;
    }

    public boolean noError() {
        return this.errorList == null || this.errorList.size() <= 0;
    }

    public boolean hasError() {
        return !this.noError();
    }

    public ValidateResult hasError(Consumer<List<ValidateError>> function) {
        if (hasError() && function != null) {
            function.accept(this.errorList);
        }
        return this;
    }

    public ValidateResult noError(Consumer<List<ValidateError>> function) {
        if (this.noError() && function != null) {
            function.accept(this.errorList);
        }
        return this;
    }

    public String getFirstError() {
        return this.errorList == null || this.errorList.size() <= 0 ? "" : this.errorList.get(0).toString();
    }

}
